package com.boby.homecamera.db

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.boby.homecamera.App
import com.boby.lib_common.BaseApplication
import java.io.File

 class DBManager private constructor(context: Context, dbPath: String)
    : SQLiteOpenHelper(context, dbPath, null, DATABASE_VERSION) {
    private val TAG = "DBManager"
    companion object {
        private const val DATABASE_VERSION = 4
        val instance by lazy {
            val dbFileDir = File(com.boby.homecamera.constant.Constant.DB_DIR)
            if(!dbFileDir.exists()){
                dbFileDir.mkdirs()
            }
            val dbFile = File(dbFileDir, "main.db") //
            DBManager(BaseApplication.instance(),"${dbFile.absoluteFile}")
        }

    }
     private var isInit = false
    @Synchronized
     fun init(){
        if(isInit){
            return
        }
        tb_video = VideoTable(writableDatabase)
        tb_user = UserTable(writableDatabase)
        tb_videoEvent = VideoEventTable(writableDatabase)

        isInit = true
    }

     lateinit var tb_video:VideoTable
         private set
     lateinit var tb_user:UserTable
         private set
     lateinit var tb_videoEvent:VideoEventTable
         private set




    override fun onCreate(db: SQLiteDatabase) {
        Log.d(TAG,"onCreate")
        VideoTable.createTable(db)
        UserTable.createTable(db)
        VideoEventTable.createTable(db)
    }

    override fun onOpen(db: SQLiteDatabase) {
        super.onOpen(db)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        if (oldVersion < 2) {
            UserTable.createTable(db)
        }
        if(oldVersion < 3) {
            VideoEventTable.createTable(db)
        }
        if(oldVersion < 4) {
            //新增字段
            VideoEventTable.upgradeToVersion4(db)
        }
    }




}
